Skip to content

feat: scan every application in a monorepo and pool one score - #19

Merged
TheOrcDev merged 5 commits into
mainfrom
feat/monorepo-workspace-scanning
Jul 27, 2026
Merged

TheOrcDev merged 5 commits into
mainfrom
feat/monorepo-workspace-scanning

Conversation

@TheOrcDev

@TheOrcDev TheOrcDev commented Jul 27, 2026 •

Copy link
Copy Markdown
Owner

Running shadscan at a monorepo root failed with "the nearest package does not declare React". It now audits every React application it finds and pools their findings into one score, with a per-package breakdown so that number is explicable.

Implements plan 014.

The decision this rests on

A React library scores 40 F with foundation and states at 0% — penalised for having no page title, favicon or theme provider, which a design system should never have. Pooling that naively means every monorepo with a packages/ui takes a hit for owning a component library.

So packages are classified, and only applications feed the score. Libraries are still scanned and reported with their own score — their accessibility findings are useful — just excluded from the pool by clearing impactsScore, which the existing category maths already filters on. No second scoring path.

Pooling reuses getCategoryScores/getTotalScore over the combined findings, so there is one scoring implementation and a single-application workspace degrades exactly to today's behaviour.

Discovery walks the tree for package.json files rather than parsing workspace globs: pnpm, npm, yarn, bun, Turborepo, Nx and Lerna all work uniformly, no YAML parser is added to a CLI with six runtime dependencies, and the CLI's project list matches the hosted scanner's.

What burn-in changed

Three things only running the code revealed:

  1. Classification keys off an application entry point, not main/exports. Internal workspace packages are routinely consumed from source through a path alias and declare no entry, so the manifest test classified them as applications — the exact outcome the split exists to prevent.
  2. Test scaffolding had to be excluded. shadcn-ui/ui returned 31 projects, most of them test/fixtures/* describing real frameworks. Discovery now mirrors the scanner's own source ignores; 31 → 17.
  3. The single-application fast path was wrong. dub has one app at apps/web beside a root with no React. "One application takes the fast path" sent it to the root and failed with UNSUPPORTED_PROJECT. Only a lone package at the root takes it now, with a regression fixture for that shape.
Project Packages Applications Score Time
dubinc/dub 6 (+6 skipped) 1 (apps/web) 21 F 23s
shadcn-ui/ui 17 (+11 skipped) 11 40 F (mixed) 3s
this repository 1 1 (root) 100 A —

No drift: dub pools to 21, exactly the apps/web score from plan 013's burn-in, and shadcn-ui/ui's apps/v4 still reports 34. This repo stays on the single-package path at 100 A. Repeated runs byte-identical.

Two defects found along the way

  • Agent work items grouped one actionable per rule id, so a pooled report silently dropped grouped items for every package after the first and emitted the rest as duplicates with no way to tell which package they meant. Now partitioned by package.
  • The scan result page keyed findings by rule id alone, which in a pooled report collapsed React rows and could resolve a work item to another package's finding.

Schema

Version 9. Findings and actionables gain packageDir, work items gain packageDir, the report gains workspace (null for single-package scans), and framework.adapter accepts mixed. The GitHub Action reads score/grade and is unaffected.

Verification

All 14 gates green. 566 CLI tests, 140 API, 152 web, e2e, build, cli:smoke. Pre-commit audit 100/100 A.

Known limits

  • Cross-package imports still resolve to a boundary; shared components are audited in their own package's scan. Explicit non-goal — widening the scan boundary touches the safety envelope and needs its own plan.
  • shadcn-ui/ui's templates/* are pooled. They are real, complete applications; excluding them would be a guess about intent, and --list-projects/--project make it inspectable and overridable.
  • The 25-application cap has not been exercised against a repository that needs it.
  • Applications are weighted near-equally regardless of size, since each contributes one finding per applicable rule. Deliberate — it keeps the score explicable from the per-package table.

Summary by CodeRabbit

  • New Features
    • Added monorepo workspace scanning with pooled scoring for applications and separate visibility for libraries.
    • Added --list-projects to preview discovered packages and --project <path> to scan a specific package.
    • Workspace reports now include workspace-level details and “mixed framework” labeling when adapters differ across applications.
  • Bug Fixes
    • Fixed pooled-workspace reporting so findings and actionables resolve correctly per package (avoids duplicate-rule mis-linking).
    • Improved work-item grouping to prevent pooled reports from dropping items after the first package.
  • Documentation
    • Updated CLI and monorepo documentation, including workspace reporting behavior and schema version notes.
  • Tests
    • Added/expanded coverage for workspace discovery and pooled workspace scoring/output.

Walk the tree for package.json manifests rather than parsing workspace
globs: it answers the same question for pnpm, npm, yarn, bun, Turborepo,
Nx and Lerna without adding a YAML parser to a CLI with six runtime
dependencies, and it keeps the CLI's project list identical to the
hosted scanner's.

Each package is classified as an application or a library, because a
React library scores zero on every document-shell rule it should never
satisfy; pooling one with applications would punish a repository for
owning a design system. The deciding signal is an application entry
point rather than a main/exports field — internal workspace packages are
routinely consumed from source through a path alias and declare no entry
at all, and keying off the manifest classified those as applications.

--list-projects prints what discovery found without scanning, so the
heuristic that decides the score is inspectable before it is trusted.
scanWorkspace scans each application sequentially and pools the findings
through the existing getCategoryScores/getTotalScore, so there is one
scoring implementation rather than two that drift, and a single-package
workspace degrades exactly to today's behaviour.

Libraries are scanned and reported but excluded from the pool by clearing
impactsScore, which the category maths already filters on. A React
library scores zero on document-shell rules it should never satisfy, so
pooling one would punish a repository for owning a design system.

Findings carry the package they came from and their evidence paths are
re-prefixed, so two packages' src/App.tsx stay distinguishable. The
report schema is version 9: findings gain packageDir, the report gains
workspace, and framework.adapter accepts "mixed" when pooled
applications disagree.

--project scans one package. A workspace with a single application still
takes the single-package path, so app-at-root layouts keep their score.
A pooled number that silently means something new is worse than no
number, so the human report now lists the packages behind it — worst
first — with libraries in their own block stating outright that they do
not count toward the score, plus skipped packages and their reasons. The
grade banner says how many applications it covers.

Also partitions agent work items by package. Grouping matched one
actionable per rule id, so in a pooled report every package after the
first silently lost its grouped items and the rest arrived as
indistinguishable duplicates — the same rule listed twice with no way to
tell an agent which package to fix. Work-item ids and titles are now
package-qualified, and single-package reports are unchanged.
Keys scan-result findings by package and rule rather than rule alone. In
a pooled report the same rule appears once per package, so a bare id
collapsed React rows and could resolve a work item to another package's
finding. Work items carry their package to make that lookup possible.

Burn-in against real monorepos changed two things. Discovery now mirrors
the scanner's source ignores, because shadcn-ui/ui returned 31 projects,
most of them test fixtures describing real frameworks that would have
been pooled into its score. And only a lone package at the repository
root takes the single-package path: counting applications instead broke
dub, whose single app lives at apps/web beside a root that declares no
React, sending the scan to the root to fail.

A workspace with no application pools its libraries rather than
reporting an unassessed score.
@vercel

vercel Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
shadscan Ready Ready Preview, Comment Jul 27, 2026 8:53pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e336a94c-0178-4cc4-b4fe-859dbabd78ba

📥 Commits

Reviewing files that changed from the base of the PR and between 0ae1cf8 and 0ce5f28.

📒 Files selected for processing (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.md

📝 Walkthrough

Walkthrough

Changes

Shadscan now discovers workspace packages, classifies applications and libraries, pools application findings, and reports package-level metadata. CLI options support package listing and single-package scans. Report schemas, human output, agent work items, and web finding lookups are workspace-aware.

Workspace scanning

Layer / File(s) Summary
Workspace discovery and pooled scan
packages/cli/src/workspace.ts, packages/cli/src/scan-workspace.ts, packages/cli/test/*workspace*
Discovers and classifies packages, records skips and truncation, scans projects, excludes libraries from application scoring, prefixes evidence paths, and produces pooled reports.
Report contracts and scoped work items
packages/cli/src/audit.ts, lib/shadscan-api/protocol.ts, app/scan/scan-result.tsx, test/shadscan-web/fixtures.ts
Adds workspace report structures, nullable package origins, mixed adapter support, schema version 9, and package-aware work-item grouping.
CLI controls and human report output
packages/cli/src/cli.ts, packages/cli/src/render-human.ts, README.md, CHANGELOG.md, plans/*
Adds --list-projects and --project, and renders workspace coverage, project scores, libraries, skipped packages, and truncation details.
Package-scoped web findings
app/scan/result-details.tsx
Keys findings and work-item lookups by package and rule to prevent cross-package collisions.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant WorkspaceDiscovery
  participant WorkspaceScanner
  participant AuditReport
  CLI->>WorkspaceDiscovery: discover workspace packages
  WorkspaceDiscovery-->>CLI: classified projects and skips
  CLI->>WorkspaceScanner: scan workspace projects
  WorkspaceScanner->>AuditReport: create pooled report
  AuditReport-->>CLI: renderable audit report
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: monorepo application scanning with pooled scoring.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/monorepo-workspace-scanning

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (7)
app/scan/result-details.tsx (1)

382-384: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use an arrow function for the short helper.

Convert getFindingKey to an arrow function to follow the repository convention. As per coding guidelines, use arrow functions for callbacks and short functions.

Proposed refactor
-function getFindingKey(packageDir: string | null, findingId: string): string {
-  return `${packageDir ?? "."}:${findingId}`;
-}
+const getFindingKey = (
+  packageDir: string | null,
+  findingId: string
+): string => `${packageDir ?? "."}:${findingId}`;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/scan/result-details.tsx` around lines 382 - 384, Convert the short
getFindingKey helper from a function declaration to an arrow-function constant
while preserving its existing parameters, return type, and key-generation
behavior.

Source: Coding guidelines

packages/cli/src/render-human.ts (1)

373-376: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Name the minimum column width.

7 is an unexplained magic number; extract it as a named constant (e.g. MIN_PACKAGE_COLUMN_WIDTH).

As per coding guidelines: "Use meaningful names instead of magic numbers, extracting constants with descriptive names".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/render-human.ts` around lines 373 - 376, Extract the
fallback value 7 in the padding calculation into a descriptively named constant
such as MIN_PACKAGE_COLUMN_WIDTH, then use that constant in the Math.max call
for workspace project package directories.

Source: Coding guidelines

packages/cli/src/audit.ts (1)

1162-1166: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cross-package work items are no longer ordered by priority.

createScopedWorkItems sorts within a package, but the final flatMap concatenates packages alphabetically, so a P3 item in apps/admin outranks a P1 item in apps/web in both the human report and the agent prompt. Consider applying the priority/disposition/impact comparator once over the concatenated list (packageDir only as the final tie-break).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/audit.ts` around lines 1162 - 1166, The final work-item
ordering in the audit aggregation must be global rather than package-grouped.
Update the flow around createScopedWorkItems to concatenate all package results
first, then apply the existing priority/disposition/impact comparator across the
complete list, using packageDir only as the final tie-break while preserving
deterministic ordering.
packages/cli/src/scan-workspace.ts (2)

89-102: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The as cast puts "mixed" into a ProjectDiscovery that cannot hold it.

ProjectDiscovery["framework"]["adapter"] has no "mixed" member, so this synthetic project now carries a value every other ProjectDiscovery consumer (e.g. the Adapter: … handoff context line and adapter-specific branching) is typed to consider impossible. Prefer threading a pooled adapter through createAuditReport explicitly over widening via assertion.

As per coding guidelines: "prefer TypeScript narrowing over type assertions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/scan-workspace.ts` around lines 89 - 102, Remove the adapter
type assertion from createWorkspaceRootProject and avoid storing a PooledAdapter
value in ProjectDiscovery.framework.adapter. Thread the pooled adapter
explicitly through createAuditReport and its downstream handoff or
adapter-specific logic, while preserving the synthetic project’s valid
ProjectDiscovery adapter type.

Source: Coding guidelines


118-136: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Packages are scanned strictly sequentially, and one failure aborts the whole workspace.

With the 25-application cap this serializes up to 25 full scans; Promise.all over workspace.projects.map(...) (or a small bounded pool) keeps output order deterministic while cutting wall time. Separately, an unexpected throw from a single scanProject fails the entire run — recording it in workspace.skipped instead would degrade more gracefully.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/scan-workspace.ts` around lines 118 - 136, The workspace
scan loop around scanProject currently runs sequentially and aborts on any
project failure. Refactor it to scan projects concurrently with Promise.all
while preserving workspace.projects output order, and catch unexpected
per-project scan errors so the affected project is recorded in workspace.skipped
rather than terminating the entire workspace scan; retain abort-signal handling
and existing project discovery behavior.
CHANGELOG.md (1)

31-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Docs overstate the single-package fast-path condition; both restate the plan's originally-planned (and later-corrected) invariant.

Per the plan's own Outcome section, "one application takes the single-package path" was the original proposal and was found wrong during burn-in (dub: one app at apps/web, root package declares no React, fell through to UNSUPPORTED_PROJECT). The shipped condition, matching cli.ts's onlyProject?.packageDir !== "." check, is narrower: only a lone application at the repository root takes the old single-package path; any other single-application layout is routed through pooled workspace scanning (same score, but workspace is populated instead of null).

  • CHANGELOG.md#L31-L34: reword to state the app must be at the workspace root to take the single-package path unchanged.
  • README.md#L214-L218: reword "A workspace containing a single application is scanned exactly as before" to specify the application must be at the repository root.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@CHANGELOG.md` around lines 31 - 34, The documentation incorrectly implies any
single-application workspace uses the single-package path. Update CHANGELOG.md
lines 31-34 and README.md lines 214-218 to state that only an application
located at the repository root takes the unchanged single-package path; single
applications elsewhere use pooled workspace scanning.
packages/cli/test/workspace.test.ts (1)

124-126: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hoist the repeated node:fs/promises dynamic imports.

mkdir/writeFile are dynamically imported separately in two different tests (and split across two import() calls in the second case) even though this module has no reason to be lazy-loaded. Import them once at the top of the file alongside path.

♻️ Proposed fix
 import path from "node:path";
+import { mkdir, writeFile } from "node:fs/promises";
 import { afterEach, describe, expect, it } from "vitest";

Then drop the per-test await import("node:fs/promises") calls at lines 124-126 and 162-164.

Also applies to: 162-164

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/test/workspace.test.ts` around lines 124 - 126, Hoist the mkdir
and writeFile imports from node:fs/promises to the top-level imports in
workspace.test.ts alongside path, then remove both per-test dynamic import calls
in the affected tests while preserving their existing filesystem operations.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/cli.ts`:
- Around line 559-586: Update the workspace scan flow around scanWorkspace and
discoverWorkspace so the workspace discovered for scanAsWorkspace is reused when
generating the report. Add an optional workspace input to scanWorkspace,
defaulting to discoverWorkspace only when no workspace is supplied, and pass the
existing workspace from cli.ts while preserving standalone callers.
- Around line 498-538: Replace the duplicated single-package output and
fail-under handling in the main scan flow with a call to emitScanReport, passing
the single-package report, options, outputFormat, and the appropriate
includeRoast value. Remove the inline JSON, prompt, human-report, and exit-code
logic so both single-package and scanAsWorkspace use the shared helper.
- Around line 580-586: Update the scanAsWorkspace branch in the CLI scan flow to
explicitly handle unsupported post-scan actions before returning: detect
options.apply or the interactive default post-scan action and surface a clear
user-facing message that these actions are unavailable for workspace/pooled
scans. Preserve report emission and the existing return behavior, while ensuring
--apply is never silently ignored.

In `@packages/cli/src/render-human.ts`:
- Around line 377-383: Update packages/cli/src/render-human.ts at lines 377-383
and 299-306 to use the count of projects actually pooled into the score instead
of workspace.applicationCount. In the workspace header, adjust the noun and
wording when the pooled units contain no applications, and reuse that same
pooled-unit count for the grade-banner coverage line.

In `@packages/cli/src/scan-workspace.ts`:
- Around line 61-68: Update getPooledAdapter and its corresponding consumers
around poolsIntoScore so empty applications derive the adapter from the
library/framework set that is actually pooled into the score, rather than
defaulting to "mixed". Preserve "mixed" only when the pooled adapter set
genuinely contains multiple or no applicable framework adapters, and ensure
human and web outputs use the corrected value.

In `@packages/cli/test/workspace.test.ts`:
- Around line 118-136: Remove the unused createWorkspaceFixture({ packages: []
}) call from the “survives a malformed package manifest” test, keeping the
rootDir fixture and malformed package setup unchanged.

In `@plans/014-monorepo-workspace-scanning.md`:
- Around line 126-129: Add the text language identifier to the fenced code block
containing the foundation, interaction, states, accessibility, and
production-polish status values, preserving its contents unchanged.

---

Nitpick comments:
In `@app/scan/result-details.tsx`:
- Around line 382-384: Convert the short getFindingKey helper from a function
declaration to an arrow-function constant while preserving its existing
parameters, return type, and key-generation behavior.

In `@CHANGELOG.md`:
- Around line 31-34: The documentation incorrectly implies any
single-application workspace uses the single-package path. Update CHANGELOG.md
lines 31-34 and README.md lines 214-218 to state that only an application
located at the repository root takes the unchanged single-package path; single
applications elsewhere use pooled workspace scanning.

In `@packages/cli/src/audit.ts`:
- Around line 1162-1166: The final work-item ordering in the audit aggregation
must be global rather than package-grouped. Update the flow around
createScopedWorkItems to concatenate all package results first, then apply the
existing priority/disposition/impact comparator across the complete list, using
packageDir only as the final tie-break while preserving deterministic ordering.

In `@packages/cli/src/render-human.ts`:
- Around line 373-376: Extract the fallback value 7 in the padding calculation
into a descriptively named constant such as MIN_PACKAGE_COLUMN_WIDTH, then use
that constant in the Math.max call for workspace project package directories.

In `@packages/cli/src/scan-workspace.ts`:
- Around line 89-102: Remove the adapter type assertion from
createWorkspaceRootProject and avoid storing a PooledAdapter value in
ProjectDiscovery.framework.adapter. Thread the pooled adapter explicitly through
createAuditReport and its downstream handoff or adapter-specific logic, while
preserving the synthetic project’s valid ProjectDiscovery adapter type.
- Around line 118-136: The workspace scan loop around scanProject currently runs
sequentially and aborts on any project failure. Refactor it to scan projects
concurrently with Promise.all while preserving workspace.projects output order,
and catch unexpected per-project scan errors so the affected project is recorded
in workspace.skipped rather than terminating the entire workspace scan; retain
abort-signal handling and existing project discovery behavior.

In `@packages/cli/test/workspace.test.ts`:
- Around line 124-126: Hoist the mkdir and writeFile imports from
node:fs/promises to the top-level imports in workspace.test.ts alongside path,
then remove both per-test dynamic import calls in the affected tests while
preserving their existing filesystem operations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4e17df7d-799d-477e-8db7-ae4c88d343c9

📥 Commits

Reviewing files that changed from the base of the PR and between 8c97bc2 and 0ae1cf8.

📒 Files selected for processing (20)
  • CHANGELOG.md
  • README.md
  • app/scan/result-details.tsx
  • app/scan/scan-result.tsx
  • lib/shadscan-api/protocol.ts
  • packages/cli/src/audit.ts
  • packages/cli/src/cli.ts
  • packages/cli/src/discovery.ts
  • packages/cli/src/render-human.ts
  • packages/cli/src/scan-workspace.ts
  • packages/cli/src/workspace.ts
  • packages/cli/test/agent-cli.test.ts
  • packages/cli/test/render-agent-prompt.test.ts
  • packages/cli/test/render-human.test.ts
  • packages/cli/test/scan-workspace.test.ts
  • packages/cli/test/workspace-fixture.ts
  • packages/cli/test/workspace.test.ts
  • plans/014-monorepo-workspace-scanning.md
  • plans/README.md
  • test/shadscan-web/fixtures.ts

Comment thread packages/cli/src/cli.ts
Comment on lines +498 to +538
/** Output and exit-code handling shared by single-package and workspace scans. */
const emitScanReport = ({
includeRoast,
options,
outputFormat,
report,
}: {
includeRoast: boolean;
options: CliOptions;
outputFormat: OutputFormat;
report: Awaited<ReturnType<typeof scanProject>>;
}): void => {
const outputReport = includeRoast ? report : stripRoasts(report);

if (outputFormat === "json") {
process.stdout.write(`${JSON.stringify(outputReport, null, 2)}\n`);
} else if (outputFormat === "prompt") {
process.stdout.write(renderAgentPrompt(outputReport));
} else {
const terminal = resolveTerminalCapabilities({
columns: process.stdout.columns,
env: {
CI: process.env.CI,
FORCE_COLOR: process.env.FORCE_COLOR,
NO_COLOR: process.env.NO_COLOR,
TERM: process.env.TERM,
},
isTTY: process.stdout.isTTY === true,
});
process.stdout.write(
renderHumanReport(outputReport, { includeRoast, terminal })
);
}

if (
options.failUnder !== undefined &&
scoreFailsThreshold(report.score, options.failUnder, report.coverage.source)
) {
process.exitCode = 1;
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

emitScanReport isn't actually used by the single-package path — the old duplicate output logic is still there.

The comment on emitScanReport says it's "shared by single-package and workspace scans," but only the scanAsWorkspace branch (line 584) calls it. Lines 588-619 still contain the identical inline JSON/prompt/human-report/fail-under logic this helper was extracted to replace. This is real duplication that can silently drift (a future change to emitScanReport won't be reflected here).

♻️ Proposed fix
   const project = await discoverProject(selectedPath);
   const report = await scanProject(project.rootDir, {
     category: options.category,
   });
-  const outputReport = includeRoast ? report : stripRoasts(report);
-
-  if (outputFormat === "json") {
-    process.stdout.write(`${JSON.stringify(outputReport, null, 2)}\n`);
-  } else if (outputFormat === "prompt") {
-    process.stdout.write(renderAgentPrompt(outputReport));
-  } else {
-    const terminal = resolveTerminalCapabilities({
-      columns: process.stdout.columns,
-      env: {
-        CI: process.env.CI,
-        FORCE_COLOR: process.env.FORCE_COLOR,
-        NO_COLOR: process.env.NO_COLOR,
-        TERM: process.env.TERM,
-      },
-      isTTY: process.stdout.isTTY === true,
-    });
-    process.stdout.write(
-      renderHumanReport(outputReport, { includeRoast, terminal })
-    );
-  }
-
-  if (
-    options.failUnder !== undefined &&
-    scoreFailsThreshold(report.score, options.failUnder, report.coverage.source)
-  ) {
-    process.exitCode = 1;
-  }
+  emitScanReport({ includeRoast, options, outputFormat, report });

Also applies to: 588-619

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cli.ts` around lines 498 - 538, Replace the duplicated
single-package output and fail-under handling in the main scan flow with a call
to emitScanReport, passing the single-package report, options, outputFormat, and
the appropriate includeRoast value. Remove the inline JSON, prompt,
human-report, and exit-code logic so both single-package and scanAsWorkspace use
the shared helper.

Comment thread packages/cli/src/cli.ts
Comment on lines +559 to +586
const workspace = options.project
? null
: await discoverWorkspace(resolvedProjectPath);
/**
* Only a lone package at the repository root takes the single-package path,
* which keeps plain projects byte-identical. Counting applications instead
* broke the very common "one app under apps/, libraries beside it" layout:
* it fell through to scanning the root, which declares no React.
*/
const onlyProject =
workspace?.projects.length === 1 ? workspace.projects[0] : null;
const scanAsWorkspace =
workspace !== null &&
workspace.projects.length > 0 &&
onlyProject?.packageDir !== ".";
const selectedPath = options.project
? await resolveProjectPath(
path.resolve(resolvedProjectPath, options.project)
)
: resolvedProjectPath;

if (scanAsWorkspace) {
const report = await scanWorkspace(resolvedProjectPath, {
category: options.category,
});
emitScanReport({ includeRoast, options, outputFormat, report });
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Workspace discovery runs twice on every pooled scan.

discoverWorkspace(resolvedProjectPath) is called here to decide scanAsWorkspace, and — per scan-workspace.ts — scanWorkspace immediately calls discoverWorkspace(rootDir, options.filesystemRoot) again internally to build the report. That's a full glob traversal plus a discoverProject call (package.json + components.json reads, framework detection) for every candidate package, done twice per invocation.

Consider letting scanWorkspace accept the already-discovered workspace to avoid the second pass, e.g. an optional workspace parameter that defaults to calling discoverWorkspace only when not supplied.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cli.ts` around lines 559 - 586, Update the workspace scan
flow around scanWorkspace and discoverWorkspace so the workspace discovered for
scanAsWorkspace is reused when generating the report. Add an optional workspace
input to scanWorkspace, defaulting to discoverWorkspace only when no workspace
is supplied, and pass the existing workspace from cli.ts while preserving
standalone callers.

Comment thread packages/cli/src/cli.ts
Comment on lines +580 to +586
if (scanAsWorkspace) {
const report = await scanWorkspace(resolvedProjectPath, {
category: options.category,
});
emitScanReport({ includeRoast, options, outputFormat, report });
return;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

--apply and the interactive post-scan menu are silently skipped for workspace/pooled scans.

The scanAsWorkspace branch returns immediately after emitScanReport, never reaching options.apply (runExplicitApply) or runDefaultPostScanAction. Running shadscan --apply at a monorepo root does nothing with no indication why — the flag the user explicitly opted into is a silent no-op.

At minimum, surface this rather than silently ignoring it, e.g.:

   if (scanAsWorkspace) {
     const report = await scanWorkspace(resolvedProjectPath, {
       category: options.category,
     });
     emitScanReport({ includeRoast, options, outputFormat, report });
+    if (options.apply) {
+      throw new ProjectDiscoveryError(
+        "--apply is not yet supported for pooled workspace scans; use --project <path> to apply against a single package."
+      );
+    }
     return;
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (scanAsWorkspace) {
const report = await scanWorkspace(resolvedProjectPath, {
category: options.category,
});
emitScanReport({ includeRoast, options, outputFormat, report });
return;
}
if (scanAsWorkspace) {
const report = await scanWorkspace(resolvedProjectPath, {
category: options.category,
});
emitScanReport({ includeRoast, options, outputFormat, report });
if (options.apply) {
throw new ProjectDiscoveryError(
"--apply is not yet supported for pooled workspace scans; use --project <path> to apply against a single package."
);
}
return;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/cli.ts` around lines 580 - 586, Update the scanAsWorkspace
branch in the CLI scan flow to explicitly handle unsupported post-scan actions
before returning: detect options.apply or the interactive default post-scan
action and surface a clear user-facing message that these actions are
unavailable for workspace/pooled scans. Preserve report emission and the
existing return behavior, while ensuring --apply is never silently ignored.

Comment on lines +377 to 383
const lines = [
"",
`${colors.bold("Workspace:")} ${workspace.kind} — ${workspace.applicationCount} application${
workspace.applicationCount === 1 ? "" : "s"
} pooled into this score`,
"",
];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Workspace copy assumes applications always exist. scanWorkspace pools libraries into the score when applicationCount === 0, so both strings report "0 applications" alongside a real pooled score.

  • packages/cli/src/render-human.ts#L377-L383: derive the header count from the projects that actually pool into the score, and adjust the wording when none of them are applications.
  • packages/cli/src/render-human.ts#L299-L306: use the same pooled-unit count for the grade-banner coverage line rather than workspace.applicationCount.
📍 Affects 1 file
  • packages/cli/src/render-human.ts#L377-L383 (this comment)
  • packages/cli/src/render-human.ts#L299-L306
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/render-human.ts` around lines 377 - 383, Update
packages/cli/src/render-human.ts at lines 377-383 and 299-306 to use the count
of projects actually pooled into the score instead of
workspace.applicationCount. In the workspace header, adjust the noun and wording
when the pooled units contain no applications, and reuse that same pooled-unit
count for the grade-banner coverage line.

Comment on lines +61 to +68
const getPooledAdapter = (applications: ScannedProject[]): PooledAdapter => {
const adapters = new Set(
applications.map((entry) => entry.report.framework.adapter)
);
const [only] = [...adapters];

return adapters.size === 1 && only ? only : "mixed";
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Library-only workspaces always report mixed.

When applications is empty (library-only workspace, handled explicitly by poolsIntoScore at Line 146), adapters is empty, adapters.size === 1 is false, and the pooled adapter falls back to "mixed" — even for a single library. Human output then prints Adapter: mixed and the web UI renders "Multiple frameworks". Derive the adapter from the set that actually pools into the score.

🐛 Proposed fix
     project: createWorkspaceRootProject(
       workspace.rootDir,
       representative,
-      getPooledAdapter(applications)
+      getPooledAdapter(applications.length > 0 ? applications : scanned)
     ),

Also applies to: 185-189

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/scan-workspace.ts` around lines 61 - 68, Update
getPooledAdapter and its corresponding consumers around poolsIntoScore so empty
applications derive the adapter from the library/framework set that is actually
pooled into the score, rather than defaulting to "mixed". Preserve "mixed" only
when the pooled adapter set genuinely contains multiple or no applicable
framework adapters, and ensure human and web outputs use the corrected value.

Comment on lines +118 to +136
it("survives a malformed package manifest", async () => {
const rootDir = await createWorkspaceFixture({
packages: [{ path: "apps/web", preset: "next" }],
});
await createWorkspaceFixture({ packages: [] });
const broken = path.join(rootDir, "packages/broken");
const { mkdir, writeFile } = await import("node:fs/promises");
await mkdir(broken, { recursive: true });
await writeFile(path.join(broken, "package.json"), "{ not json");

const workspace = await discoverWorkspace(rootDir);

expect(workspace.projects.map((project) => project.packageDir)).toEqual([
"apps/web",
]);
expect(
workspace.skipped.some((skip) => skip.packageDir === "packages/broken")
).toBe(true);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the unused fixture creation.

Line 122's createWorkspaceFixture({ packages: [] }) result is never used by this test; it just creates and later cleans up an unrelated temp workspace. Looks like a leftover from copy/paste.

🧹 Proposed fix
     const rootDir = await createWorkspaceFixture({
       packages: [{ path: "apps/web", preset: "next" }],
     });
-    await createWorkspaceFixture({ packages: [] });
     const broken = path.join(rootDir, "packages/broken");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it("survives a malformed package manifest", async () => {
const rootDir = await createWorkspaceFixture({
packages: [{ path: "apps/web", preset: "next" }],
});
await createWorkspaceFixture({ packages: [] });
const broken = path.join(rootDir, "packages/broken");
const { mkdir, writeFile } = await import("node:fs/promises");
await mkdir(broken, { recursive: true });
await writeFile(path.join(broken, "package.json"), "{ not json");
const workspace = await discoverWorkspace(rootDir);
expect(workspace.projects.map((project) => project.packageDir)).toEqual([
"apps/web",
]);
expect(
workspace.skipped.some((skip) => skip.packageDir === "packages/broken")
).toBe(true);
});
it("survives a malformed package manifest", async () => {
const rootDir = await createWorkspaceFixture({
packages: [{ path: "apps/web", preset: "next" }],
});
const broken = path.join(rootDir, "packages/broken");
const { mkdir, writeFile } = await import("node:fs/promises");
await mkdir(broken, { recursive: true });
await writeFile(path.join(broken, "package.json"), "{ not json");
const workspace = await discoverWorkspace(rootDir);
expect(workspace.projects.map((project) => project.packageDir)).toEqual([
"apps/web",
]);
expect(
workspace.skipped.some((skip) => skip.packageDir === "packages/broken")
).toBe(true);
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/test/workspace.test.ts` around lines 118 - 136, Remove the
unused createWorkspaceFixture({ packages: [] }) call from the “survives a
malformed package manifest” test, keeping the rootDir fixture and malformed
package setup unchanged.

Comment on lines +126 to +129
```
foundation(0%) interaction(30%) states(0%)
accessibility(100%) production-polish(100%)
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add a language to the fenced code block.

markdownlint (MD040) flags this fence as missing a language identifier.

🧹 Proposed fix
-```
+```text
 foundation(0%)  interaction(30%)  states(0%)
 accessibility(100%)  production-polish(100%)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
```
foundation(0%) interaction(30%) states(0%)
accessibility(100%) production-polish(100%)
```
🧰 Tools
🪛 markdownlint-cli2 (0.23.0)

[warning] 126-126: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@plans/014-monorepo-workspace-scanning.md` around lines 126 - 129, Add the
text language identifier to the fenced code block containing the foundation,
interaction, states, accessibility, and production-polish status values,
preserving its contents unchanged.

Source: Linters/SAST tools

@TheOrcDev
TheOrcDev merged commit b6ce127 into main Jul 27, 2026
6 checks passed
@TheOrcDev
TheOrcDev deleted the feat/monorepo-workspace-scanning branch July 27, 2026 21:06
@coderabbitai coderabbitai Bot mentioned this pull request Jul 28, 2026

This branch was successfully deployed

1 active deployment
Preview — 0ce5f282 Deployed Jul 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant